package org.jeecg.modules.demo.food.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.compages.entity.MaterialCompages;
import org.jeecg.modules.demo.compages.service.IMaterialCompagesService;
import org.jeecg.modules.demo.food.entity.Material;
import org.jeecg.modules.demo.food.service.IMaterialService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.tools.MyTestUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: material
 * @Author: jeecg-boot
 * @Date:   2020-04-09
 * @Version: V1.0
 */
@Api(tags="material")
@RestController
@RequestMapping("/food/material")
@Slf4j
public class MaterialController extends JeecgController<Material, IMaterialService> {
	@Autowired
	private IMaterialService materialService;
	
	@Autowired
	private ISysDepartService sysDepartService;
	
	@Autowired
	private IMaterialCompagesService materialCompagesService;
	
	/**
	 * 分页列表查询
	 *
	 * @param material
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "material-分页列表查询")
	@ApiOperation(value="material-分页列表查询", notes="material-分页列表查询")
	@GetMapping(value = "/list")	
	public Result<?> queryPageList(Material material,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Material> queryWrapper = QueryGenerator.initQueryWrapper(material, req.getParameterMap());
		queryWrapper.eq("delete_flag", 0);
		Page<Material> page = new Page<Material>(pageNo, pageSize);
		IPage<Material> pageList = materialService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param material
	 * @return
	 */
	@AutoLog(value = "material-添加")
	@ApiOperation(value="material-添加", notes="material-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("material:add")
	public Result<?> add(@RequestBody Material material) {
		materialService.save(material);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param material
	 * @return
	 */
	@AutoLog(value = "material-编辑")
	@ApiOperation(value="material-编辑", notes="material-编辑")
	@PutMapping(value = "/edit")
	//@RequiresPermissions("material:edit")
	public Result<?> edit(@RequestBody Material material) {
		materialService.updateById(material);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "material-通过id删除")
	@ApiOperation(value="material-通过id删除", notes="material-通过id删除")
	@DeleteMapping(value = "/delete")
	@RequiresPermissions("material:delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		//materialService.removeById(id);
		List<Integer> list=new ArrayList<Integer>();
		list.add(Integer.parseInt(id));
		int i=materialService.upDeleteFLag(list);
		if(i>0)
			return Result.ok("删除成功!");
		else
			return Result.ok("删除失败!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "material-批量删除")
	@ApiOperation(value="material-批量删除", notes="material-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@RequiresPermissions("material:delete")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		//this.materialService.removeByIds(Arrays.asList(ids.split(",")));
		List list=Arrays.asList(ids.split(","));
		int i=materialService.upDeleteFLag(list);
		if(i>0)
			return Result.ok("批量删除成功!");
		else
			return Result.ok("批量删除失败!");
		//return Result.ok("批量删除成功!");
	}
	
	
	/**
	 *  批量组合
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "material-批量组合")
	@ApiOperation(value="material-批量组合", notes="material-批量组合")
	@DeleteMapping(value = "/compages")
	@RequiresPermissions("material:compages")
	public Result<?> compages(@RequestParam(name="ids",required=true) String ids) {
		//this.materialService.removeByIds(Arrays.asList(ids.split(",")));
		List list=Arrays.asList(ids.split(","));
		Iterator<String> iterator=list.iterator();
		
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId=sysUser.getId();
		SysUser User=sysDepartService.queryUserById(userId);
		String createBy=User.getCreateBy();
		SysUser User1=sysDepartService.queryCreateBy(createBy);
		//获取第二个A之前的orgCode数据
		String orgCode=User1.getOrgCode();
		
		String names="";
		BigDecimal retailprice=new BigDecimal("0");
		BigDecimal lowprice=new BigDecimal("0");
		BigDecimal presetpriceone=new BigDecimal("0");
		
		if(list.size()<2)
			return Result.error("组合商品数量必须大于2个!");
					
		BigDecimal storage=new BigDecimal("0");
		List<BigDecimal> bList=new ArrayList<>();
		
		boolean already=false;
				
		List<Material> materials=new ArrayList<>();
		
		while (iterator.hasNext()) {
			String id=iterator.next();
			Material material1 = materialService.getById(id);
			materials.add(material1);
			names = names + "+" + material1.getName();
			if (material1.getRetailprice() != null)
				retailprice=retailprice.add(material1.getRetailprice());
			if (material1.getLowprice() != null)
				lowprice=lowprice.add(material1.getLowprice());
			if (material1.getPresetpriceone() != null)
				presetpriceone=presetpriceone.add(material1.getPresetpriceone());
			
			BigDecimal b1=material1.getStorage();

			if (b1!=null&&b1.floatValue()>storage.floatValue())
				bList.add(b1);
			
			if(material1.getCombination()==1)
				already=true;
		}

		if(bList.size()>0)
			storage=Collections.min(bList);
		
		if(already)
			return Result.error("已经组合的商品不能再组合!");
		
		Material material=new Material();
		material.setName(names);
		material.setRetailprice(retailprice);
		material.setLowprice(lowprice);
		material.setPresetpriceone(presetpriceone);
		material.setCreateBy(createBy);
		material.setSysOrgCode(orgCode);
		material.setStorage(storage);
		
		int i=materialService.insertCompages(material, materials);
		if(i>0)
			return Result.ok("批量组合成功!");
		else
			return Result.error("批量组合失败!");
	}
	
	@AutoLog(value = "material-批量出售")
	@ApiOperation(value="material-批量出售", notes="material-批量出售")
	@DeleteMapping(value = "/sale")
	@RequiresPermissions("material:sale")
	public Result<?> sale(@RequestParam(name="ids",required=true) String ids) {
		List list=Arrays.asList(ids.split(","));

		int i=materialService.sale(list, new BigDecimal("1"));
		List list2=new ArrayList<>();
		list2.add(23);
		List list3=materialCompagesService.select(list2);
		System.out.println("kkkkkkkkkkkkk");
		MyTestUtil.print(list3);
		if(i>0)
			return Result.ok("批量出售成功!");
		else if(i==-2)
			return Result.error("库存不够!");
		else
			return Result.error("批量出售失败!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "material-通过id查询")
	@ApiOperation(value="material-通过id查询", notes="material-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Material material = materialService.getById(id);
		if(material==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(material);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param material
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Material material) {
        return super.exportXls(request, material, Material.class, "material");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Material.class);
    }

}
